﻿using UnityEngine;
using System;

public class SocketMsgCreater 
{
	//For Seek
	public int Position { get; protected set; } = 0;

	public byte[] Buffer { get; protected set; } 


	public SocketMsgCreater(int msgLength)
	{
		//消息字符串至少为 2 * sizeof(Int32)
		if (msgLength > 0)
		{
			Buffer = new byte[msgLength];
		}
		else
		{
			Debug.LogError("SocketMsgCreater Constructor Invail Length");
		}
		this.Clear();
	}
	
	public void Clear()
	{
		Position = 0;
	}

	protected void ReSize(int length) {
		if (length > Buffer.Length) {
			var newlen = Buffer.Length * 2 >= length ? Buffer.Length * 2 : length;
			byte[] temp = new byte[newlen];
			Array.Copy(Buffer, temp, Buffer.Length);
			Buffer = temp;
		}
	}

	public void Write(byte[] bytes) {

		var len = bytes.Length;
		ReSize(Position + len);
		Array.Copy(bytes, 0, Buffer, Position, len);
		Position += len;
	}


	public void Write(string str)
	{
		byte[] strByte = System.Text.Encoding.UTF8.GetBytes(str);
		this.Write(strByte);
	}

	public void Write(int integer)
	{
		byte[] intByte = BitConverter.GetBytes(integer);
		this.Write(intByte);
	}

}
